//
//  ZMNewVersion.swift
//  LinShen
//
//  Created by 刘亿前 on 2022/8/14.
//

import Foundation

/// 版本信息
struct AppVersionModel: HandyJSON {
    /// 下载地址
    var url = ""
    /// 是否强制更新
    var isForceUpdate = false
    /// 版本号
    var versionNo = ""
    /// 版本编号
    var versionId = 0
    /// 描述
    var desc = ""
    /// 是否提醒
    var isTip = false
}

class ZMNewVersion {
    static let share = ZMNewVersion()
    let disposeBag = DisposeBag()
    var versionInfo = AppVersionModel()
    
    func checkVersion() {
        ZMNewVersionAPI.app_version.rxRequestNullAble(type: AppVersionModel.self).subscribe(onNext:{ resp in
            if let data = resp {
                self.versionInfo = data
                if let val = UserDefaults.standard.object(forKey: "VersionInfo") as? String,
                   let info = JSONDeserializer<AppVersionModel>.deserializeFrom(json: val) {
                    if info.versionId == data.versionId && info.isTip {
                        /// 缓存版本 == 最新版本 && 不在提醒
                        self.loadBannerPop()
                        return
                    }
                }
                if data.versionId > AppBuildVersion.zm.hk_toInt() {
                    /// 最新版本 > 当前版本
                    ZMNewVersionView.showVersion(data) {
                        self.loadBannerPop()
                    }
                } else {
                    self.loadBannerPop()
                }
            }
        }).disposed(by: disposeBag)
    }
    
    // 加载公告
    func loadBannerPop() {
        HomeAPI.banner_pop([:]).rxRequest(type: [String].self).subscribe(onNext:{ [unowned self] resp in
            if resp.count > 0 {
                let v = ZMUtil.loadNibViewFullScreen(nibName: PopBanner.self)
                v.imgs = resp
                if let vc = AppHelper.currentNav()?.children.last {
                    vc.view.addSubview(v)
                }
            }
        }).disposed(by: disposeBag)
    }
}
